﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using YArchitech.Revit;

namespace YArchitech.Plumbing
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class SystemView : IExternalCommand
	{
		public Result Execute(ExternalCommandData cmdData, ref string msg, ElementSet elems)
		{
			UIDocument activeUIDocument = cmdData.Application.ActiveUIDocument;
			Selection selection = activeUIDocument.Selection;
			Document document = cmdData.Application.ActiveUIDocument.Document;
			if (!YJKRevitTools.ViewCheck(activeUIDocument, new List<ViewType>
			{
				(ViewType)1,
				(ViewType)2
			}))
			{
				return Autodesk.Revit.UI.Result.Cancelled;
			}
			Transaction transaction = null;
			Result result;
			try
			{
				transaction = new Transaction(document, "系统浏览");
				transaction.Start();
				SystemViewForm systemViewForm = new SystemViewForm(document, selection);
				systemViewForm.ShowDialog();
				if (systemViewForm.DialogResult == DialogResult.OK)
				{
					string strSysName = systemViewForm.lstSysName.SelectedItem.ToString();
					if (systemViewForm.chkView3D.Checked)
					{
						View3D view3D = systemViewForm.GetView3D(strSysName);
						transaction.Commit();
						if (view3D == null)
						{
							return Autodesk.Revit.UI.Result.Failed;
						}
						activeUIDocument.ActiveView = view3D;
					}
					else
					{
						transaction.Commit();
					}
				}
				else
				{
					transaction.Commit();
				}
				result = Autodesk.Revit.UI.Result.Succeeded;
			}
			catch (Exception ex)
			{
				ex.ToString();
				if (transaction != null && transaction.HasStarted() && !transaction.HasEnded())
				{
					transaction.RollBack();
				}
				result = Autodesk.Revit.UI.Result.Failed;
			}
			return result;
		}
	}
}
